-- ======================================================================
-- Hell Lua Bus
-- 
-- Copyright 2012-2014 Hell-Prototypes
--
-- http://www.hellprototypes.com/
--
-- This is free software, licensed under the terms of the GNU General
-- Public License as published by the Free Software Foundation.
-- ======================================================================
printf = require "mod_print"
iHEX = require "mod_iHEX"

bin_file = arg[1]

if bin_file == nil then
	print("Error: Need Bin file name")
	return
end

local f = assert(io.open(bin_file, "rb"))
if f == nil then
	print("Fail to read file : " .. bin_file)
	return
end

local C_Array = ""
C_Array = C_Array .. "const uint8_t Bin2Array[] PROGMEM = {\r\n"

local block = 16
while true do
    local bytes = f:read(block)
    if not bytes then break end
	C_Array = C_Array .. string.format("    ")
    for byte in string.gmatch(bytes, ".") do
		local hex = string.format("%02x,", string.byte(byte))
	    C_Array = C_Array .. "0x" .. string.upper(hex)
    end
    C_Array = C_Array .. string.format("\r\n")
end
C_Array = C_Array .. "};"
print(C_Array)

f:close()

local file_name = bin_file .. ".c"
local file_w = io.open(file_name, "wb")
file_w:write(C_Array)
file_w:close()
